<template>
  <div class='container'>
    <el-card>
      <div slot="header">
        <span>试题录入</span>
      </div>
      <el-form ref="questionFormData" :model="questionFormData" :rules="rules" >
        <el-form-item label="学科：" prop="subjectID">
          <el-select placeholder="请选择" style="width: 400px" v-model="questionFormData.subjectID" @change="handleSubjectChange" >
            <el-option v-for="obj in subjectList" :key="obj.value" :label="obj.label" :value="obj.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID">
          <el-select placeholder="请选择" style="width: 400px" v-model="questionFormData.catalogID">
            <el-option v-for="obj in catalogList" :key="obj.value" :label="obj.label" :value="obj.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID" >
          <el-select placeholder="请选择" style="width: 400px" v-model="questionFormData.enterpriseID" >
            <el-option v-for="obj in companysList" :key="obj.id" :label="obj.shortName" :value="obj.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市：" prop="province">
          <el-select placeholder="请选择" style="width: 198px; margin-right: 4px" v-model="questionFormData.province" @change="getCitysList()">
            <el-option v-for="(city,index) in provincesList" :key="index" :label="city" :value="city"
           ></el-option>
          </el-select>
          <el-select placeholder="请选择区域" style="width: 198px" v-model="questionFormData.city">
            <el-option v-for="(item, index) in citysList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向：" prop="direction">
          <el-select placeholder="请选择" style="width: 400px" v-model="questionFormData.direction">
            <el-option v-for="(item, index) in directionsList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型：" prop="questionType">
          <!-- @change="questionTypeChange" -->
          <el-radio-group v-model="questionFormData.questionType"  >
            <el-radio v-for="item in questionTypeList" :key="item.value" :label="item.value" @change="questionTypeChange">{{item.label}}</el-radio>
            <!-- <el-radio :label="2">多选</el-radio>
            <el-radio :label="3">简答</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="questionFormData.difficulty" @change="difficultyChange">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干：" prop="question" >
          <!-- 富文本编辑器 -->
          <editor v-model="questionFormData.question" ref="questionContent" @change="onEditorQuestionChange"></editor>
        </el-form-item>
          <el-form-item
           v-show="optionsItem"
          v-for="(domain, index) in questionFormData.options"
          :label="index > 0 ? '':'选项:'"
          :key="index"
          :prop="'options.' + index + '.value'"
        >
          <div class="options-box">
            <el-radio v-if="btnAddOptions" v-model="radioOptions" :label="String.fromCharCode(65+index)" @change="changeRadioData(domain,index)">{{ String.fromCharCode(65+index)}}：</el-radio>
            <el-checkbox v-else v-model="domain.isRight">{{ String.fromCharCode(65+index)}}：</el-checkbox>
            <el-input v-model="domain.title"></el-input>
            <uploadImg  style="margin-left: 10px" v-model="domain.img" :imgIndex="index"  @uploadImgData="uploadImgData"></uploadImg>
          </div>

        </el-form-item>
        <el-button @click="addDomain(questionFormData.options.length)" type="danger" size="small" style="margin-left: 120px; margin-bottom: 30px"  :disabled="btnAddOptions"
        v-show="optionsItem"
         >+增加选项与答案名</el-button>
        <el-form-item label="解析视频：" prop="videoURL">
            <el-input style="width: 400px" v-model="questionFormData.videoURL"></el-input>
        </el-form-item>
         <el-form-item label="答案解析：" prop="answer">
            <!-- 富文本编辑器 -->
          <editor v-model="questionFormData.answer" ref="editorContent" @change="onEditorAnswerChange"></editor>
        </el-form-item>

        <el-form-item label="题干备注：" prop="remarks">
          <el-input type="textarea" :rows="3" style="width: 400px" v-model="questionFormData.remarks"></el-input>
        </el-form-item>
        <el-form-item label="试题标签：" prop="tags">
          <el-select
          multiple
          filterable
          allow-create
          default-first-option
        placeholder="请选择试题标签" style="width: 400px"
         v-model="questionFormData.tags" @change="changeTagData">
        <el-option
          v-for="item in tagsList"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
        </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <el-row style="margin-left: 80px">
        <el-col :span="6">
          <el-button type="primary" @click="addQuestionSubmit">确认提交</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import editor from '../components/editor'
import uploadImg from '../components/uploadImg'
import { simple } from '@/api/hmmm/subjects' // 学科
import { simple as catalogSimple } from '@/api/hmmm/directorys' // 目录
import { list } from '@/api/hmmm/companys' // 公司
import { provinces, citys } from '@/api/hmmm/citys' // 引入城市和对应的区域
import { direction } from '@/api/hmmm/constants'
import { add, detail, update } from '@/api/hmmm/questions'
var optionsList = [{ // 选项
  code: 'A', // 代码
  title: '', // 标题
  img: '', // 图片URL
  isRight: false // 是否正确答案
}, { // 选项
  code: 'B', // 代码
  title: '', // 标题
  img: '', // 图片URL
  isRight: false // 是否正确答案
}, { // 选项
  code: 'C', // 代码
  title: '', // 标题
  img: '', // 图片URL
  isRight: false // 是否正确答案
}, { // 选项
  code: 'D', // 代码
  title: '', // 标题
  img: '', // 图片URL
  isRight: false // 是否正确答案
}]
export default {
  data () {
    return {
      dynamicValidateForm: {
        domains: [{
          value: ''
        }],
        email: ''
      },
      difficultyRadio: 1, // 难度三选互斥，默认label为1的选项
      questionFormData: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: optionsList,
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      },
      questionTypeList: [
        {
          label: '单选',
          value: '1'
        },
        {
          label: '多选',
          value: '2'
        },
        {
          label: '简答',
          value: '3'
        }
      ],
      // 表单校验
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ]
      },
      subjectList: [], // 学科列表
      catalogList: [], // 目录列表
      companysList: [], // 公司列表
      provincesList: [], // 城市列表
      citysList: [], // 城市区域列表
      directionsList: [], // 方向列表
      selectorNum: 4, // 选项
      btnAddOptions: true, // 控制添加选项按钮
      optionsItem: true, // 控制选项组件创建与销毁
      radioOptions: '', // 控制单选按钮
      tagsList: []

    }
  },
  components: {
    editor,
    uploadImg
  },
  created () {
    this.simple()
    this.handleCompanyChange() // 获取公司列表
    this.getProvincesList() // 获取城市列表
    this.directionsList = direction // 方向常量赋值
    if (this.$route.query && this.$route.query.id) {
      this.getDetailList(this.$route.query)
    }
  },
  methods: {
    changeTagData () {
      console.log(this.questionFormData.tags)
    },
    addDomain (i) {
      this.questionFormData.options.push({ // 选项
        code: String.fromCharCode(65 + i), // 代码
        title: '', // 标题
        img: '', // 图片URL
        isRight: false // 是否正确答案
      })
    },
    changeRadioData (item, i) {
      const options = this.questionFormData.options
      options.forEach(data => {
        if (item.code === data.code) {
          data.isRight = true
        } else {
          data.isRight = false
        }
      })
    },
    // 获取学科列表
    async simple () {
      try {
        const { data } = await simple()
        this.subjectList = data
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 选择学科，调用目录循环展示
    async handleSubjectChange () {
      try {
        const { data } = await catalogSimple(this.questionFormData.subjectID)
        this.catalogList = data
        this.questionFormData.catalogID = ''
      } catch (error) {
        console.log(error)
      }
    },
    // 企业选择目录
    async handleCompanyChange () {
      try {
        const result = await list({
          pagesize: 10000
        })
        this.companysList = result.data.items
      } catch (error) {
        console.log(error)
      }
    },
    // 获取城市列表
    getProvincesList () {
      this.provincesList = provinces()
    },
    // 获取城市区域列表
    getCitysList () {
      this.citysList = citys(this.questionFormData.province)
      this.questionFormData.city = '' // 置空二级选项内容
    },
    // 题型发生变化
    questionTypeChange (value) {
      this.questionFormData.questionType = value
      this.btnAddOptions = value !== '2' // 不是2多选，添加按钮禁用
      this.optionsItem = value !== '3' // 不是3简答，就显示

      const num = this.questionFormData.options.length - 4
      this.questionFormData.options.splice(4, num)
      this.questionFormData.options.forEach(item => {
        item.title = ''
        item.isRight = false
        item.img = ''
      })
      this.radioOptions = ''
    },
    // 难度发生变化
    difficultyChange (value) {
      this.questionFormData.difficulty = value
    },
    // 题干富文本
    onEditorQuestionChange (content) {
      // 拿到富文本内容 提交表单时用
      this.questionFormData.question = content
    },
    // 答案解析富文本
    onEditorAnswerChange (content) {
      // 拿到富文本内容 提交表单时用
      this.questionFormData.answer = content
    },
    uploadImgData (imgURL, index) {
      this.questionFormData.options[index].img = imgURL
    },
    async addQuestionSubmit () {
      await this.$refs.questionFormData.validate()

      try {
        const _tag = this.questionFormData.tags
        console.log(_tag)
        const _questionType = this.questionFormData.questionType
        const _difficulty = this.questionFormData.difficulty
        this.questionFormData.questionType = _questionType
        this.questionFormData.difficulty = _difficulty
        this.questionFormData.tags = _tag.join(',')
        if (this.$route.query && this.$route.query.id) {
          this.questionFormData.id = Number(this.$route.query.id)
          await update(this.questionFormData)
          this.$message.success('更新成功')
          this.$router.push('/questions/choice')
        } else {
          const result = await add(this.questionFormData)
          this.$message.success('提交题目成功')
          if (result.status === 200) {
            this.$router.push('/questions/list')
          }
        }
      } catch (error) {
        this.$message.error(error)
      }
    },
    async getDetailList (id) {
      try {
        const { data } = await detail(id)
        // data.questionType = Number(data.questionType)
        this.questionFormData = data

        if (data.questionType === '1') {
          this.btnAddOptions = true
          this.optionsItem = true
          this.questionFormData.options.forEach(item => {
            if (item.isRight === 1) {
              this.radioOptions = item.code
            }
          })
        } else if (data.questionType === '2') {
          this.btnAddOptions = false
          this.optionsItem = true
          this.questionFormData.options.forEach(item => {
            if (item.isRight === 1) {
              item.isRight = true
            } else {
              item.isRight = false
            }
          })
        } else {
          this.btnAddOptions = false
          this.optionsItem = false
        }
        const _tags = this.questionFormData.tags.split(',')
        // console.log(_tags.split(','))
        const _array = []
        _tags.forEach(item => {
          const obj = {}
          obj.value = item
          obj.label = item
          _array.push(obj)
        })
        this.tagsList = _array
        this.questionFormData.tags = _tags
        console.log(this.tagsList)
        this.$nextTick(() => {
          this.$refs.questionContent.content = data.question
          this.$refs.editorContent.content = data.answer
        })
        console.log(this.questionFormData)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" scoped lang="scss">
.container {
  padding: 20px;
  ::v-deep .el-form-item__label {
    width: 120px!important;
  }
  ::v-deep .el-form-item__content {
    margin-left: 120px!important;
  }
  .options-box {
    display: flex;
    align-items: center;
    .el-input {
      width: 240px;
      margin-left: 20px;
    }
  }
}
</style>
